import urllib.request
import os
import re
from bs4 import BeautifulSoup as bs


def url_open(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0')
    response = urllib.request.urlopen(url)
    html = response.read()
    return html


def get_page(url):
    '''根据隐藏的标签内容获取当前最新页码'''

    # a = html.find('current-comment-page').text
    # print(a)
    html = url_open(url)
    soup = bs(html, 'html.parser')
    page = soup.find(class_='current-comment-page').text[1:-1]
    return page


def find_imgs(url):
    '''根据url找到图片地址并返回'''

    # html = url_open(url)
    # img_addrs = []
    # soup = bs(html,'html.parser')
    #
    # for each in soup.find_all(src=re.compile("sinaimg")):
    #     print(each)

    html = url_open(url).decode('utf-8')
    img_addrs = []
    a = html.find('img src=')

    while a != -1:
        b = html.find('.jpg', a, a + 255)
        if b != -1:
            pic = html[a + 9:b + 4]
            if pic.find('niuza') == -1:
                img_addrs.append(pic)
        else:
            b = a + 9
        a = html.find('img src=', b)

    return img_addrs


def save_imgs(folder, ims_addrs):
    '''将获取到的图片url保存在指定的本地'''
    for each in ims_addrs:
        filename = each.split('/')[-1]
        with open(filename, 'wb') as f:
            img = url_open(each)
            f.write(img)


def download_mm(folder='ooxx', pages=10):
    folder = 'D:' + os.sep + folder

    if not (os.path.exists(folder)):
        os.mkdir(folder)
        os.chdir(folder)

    url = 'http://jandan.net/ooxx/'

    page_num = int(get_page(url))
    for i in range(pages):
        page_num -= i
        page_url = url + 'page-' + str(page_num) + '#comments'
        ims_addrs = find_imgs(page_url)
        save_imgs(folder, ims_addrs)


if __name__ == '__main__':
    # http://jandan.net/ooxx/page-2205#comments
    # http://ww3.sinaimg.cn/mw600/005vbOHfgw1f9m4d4p3ubj31jk114qhr.jpg
    download_mm()

# html = ' img src='
# b = html.find('img',0,0)
# print(b)
